package org.tio.showcase.test;

import io.reactivex.subjects.PublishSubject;
import io.reactivex.subjects.Subject;
import org.tio.websocket.client.WebSocket;
import org.tio.websocket.client.WsClient;
import org.tio.websocket.client.config.WsClientConfig;
import org.tio.websocket.common.WsPacket;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern;

/**
 * https://www.tiocloud.com/tio/docs/t-io/demo/tiowsc/
 *
 * @author chenck
 * @date 2025/3/11 16:45
 */
public class TextWebSocketClient {

    public static void main(String[] args) throws Exception {
        Map<Integer, Boolean> sent = new ConcurrentHashMap<>();
        int total = 1000;

        Subject<Object> complete = PublishSubject.create().toSerialized();
        complete
                .buffer(total)
                .subscribe(
                        x -> {
                            Boolean all = sent.values().stream().reduce(true, (p, c) -> p && c);
                            if (all) {
                                System.out.println("All sent success! ");
                            }
                        });

        WsClient echo =
                WsClient.create(
                        "ws://localhost:9326/?encoding=text",
                        new WsClientConfig(
                                e -> System.out.println("opened"),
                                e -> {
                                    WsPacket data = e.data;
                                    String dataStr = data.getWsBodyText();
                                    if (Pattern.compile("\\d+").matcher(dataStr).matches()) {
                                        int i = Integer.parseInt(dataStr);
                                        sent.put(i, true);
                                        complete.onNext(i);
                                    } else {
                                        System.out.println("recv: " + dataStr);
                                    }
                                },
                                e -> System.out.printf("on close: %d, %s, %s\n", e.code, e.reason, e.wasClean),
                                e -> System.out.println(String.format("on error: %s", e.msg)),
                                Throwable::printStackTrace));

        WebSocket webSocket = echo.connect();

        for (int i = 0; i < total; i++) {
            webSocket.send("" + i);
            sent.put(i, false);
            System.out.println("sent: " + i);
        }
    }
}
